package com.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * 454. 四数相加 II
 * 分两组 两数组和存入Map然后再 一重循环通过map查找
 *
 * @author fy
 * @date 2022/4/8 11:31
 */
public class Solution454_1 {

    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        int res = 0;
        if (nums1 == null || nums2 == null || nums3 == null || nums4 == null) {
            return res;
        }
        if (nums1.length == 0 || nums2.length == 0 || nums3.length == 0 || nums4.length == 0) {
            return res;
        }

        Map<Integer, Integer> sumMap = new HashMap<>();
        for (int num1 : nums1) {
            for (int num2 : nums2) {
                int sum = num1 + num2;
                sumMap.put(sum, sumMap.getOrDefault(sum, 0) + 1);
            }
        }

        Map<Integer, Integer> sum2Map = new HashMap<>();
        for (int num3 : nums3) {
            for (int num4 : nums4) {
                int sum = num3 + num4;
                sum2Map.put(sum, sum2Map.getOrDefault(sum, 0) + 1);
            }
        }

        for (Integer num : sumMap.keySet()) {
            if (sum2Map.containsKey(-num)) {
                res += sumMap.get(num) * sum2Map.get(-num);
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[] nums1 = new int[]{1, 2};
        int[] nums2 = new int[]{-2, -1};
        int[] nums3 = new int[]{-1, 2};
        int[] nums4 = new int[]{0, 2};

//        int[] nums1 = new int[]{0};
//        int[] nums2 = new int[]{0};
//        int[] nums3 = new int[]{0};
//        int[] nums4 = new int[]{0};

        int res = new Solution454_1().fourSumCount(nums1, nums2, nums3, nums4);
        System.out.println(res);
    }

}
